

const http = require('http')
const cheerio = require('cheerio')
const nodemailer = require('nodemailer')
const schedule = require('node-schedule')

const iconv = require('iconv-lite')
const BufferHelper = require('bufferhelper')

const SCHEDULE_RULE = '1 30 6 * * *'


const url  = 'http://tianqi.2345.com/today-71144.htm'

http.get(url, res => {
	let html = ''
	let bufferHelper = new BufferHelper()
	res.on('data', chunk => {
		bufferHelper.concat(chunk)
	})
	res.on('end', () => {
		let zzc = iconv.decode(bufferHelper.toBuffer(),'GBK')
		let $ = cheerio.load(zzc)
		var watherArrays = []
		let centigrade = $('.temperature').text()
		let situation = $('.time-now .parameter li')
		for(let i = 0; i < situation.length; ++i){
			var wind = $(situation[2]).children().text()
			var windS = $(situation[3]).children().text()
			var humidity = $(situation[4]).children().text()
			var UltravioletRays = $(situation[6]).children().text()
		}
		let suggest = $('.emoticon span').text()
		let evaluate = $('.ord1 span').text()

		let day = $('.time-main dt').text()
		console.log('-----正在给姐姐发送邮件------')

		watherArrays.push({
			'centigrade': centigrade,
			'wind': wind,
			'windS': windS,
			'humidity': humidity,
			'UltravioletRays': UltravioletRays,
			'evaluate': evaluate,
			'suggest': suggest
		})
		schedule.scheduleJob(SCHEDULE_RULE, () => {
			sendEmail(watherArrays)
		})
	})
})

function sendEmail(watherArrays){
	let transporter = nodemailer.createTransport({
		service: 'qq',
		auth: {
			user: '1761997216@qq.com',
			pass: 'jacnlcfehnmudjda'
		}
	})

	var mailOptions = {  
		from: '1761997216@qq.com', 
		to: '1144832761@qq.com', 
		subject: `今日天气`,  
		html: ` <strong>姐姐下面是今天北京海淀区的天气</strong>
				<p>白天到晚上 : ${watherArrays[0].evaluate}</p>
				<p>今日天气 : ${watherArrays[0].centigrade}</p>
				<p>${watherArrays[0].wind}</p>
				<p>${watherArrays[0].windS}</p>
				<p>${watherArrays[0].humidity}</p>
				<p>${watherArrays[0].UltravioletRays}</p>
				<strong>${watherArrays[0].suggest}</strong>`
	}
	transporter.sendMail(mailOptions, function (err, info) {  
	    if (err) {  
	      console.log(err);  
	      return;  
	    }  
	    console.log('发送成功');
	  })
}

